package com.otv.core;

import java.io.IOException;
import java.security.Principal;
import java.util.Calendar;
import java.util.Date;

import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.otv.model.User;

public class AccessFilterCore implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		String requestURI = req.getRequestURI();
		HttpServletResponse res = (HttpServletResponse) response;  
		Principal userPrincipal = req.getUserPrincipal();
		HttpSession httpSession = ((HttpServletRequest) request).getSession();
		String requestedUrl = req.getRequestURL().toString();
		boolean containsAdmin = requestedUrl.contains("admin");  

		Date internetTime = null;
		try {
			internetTime = CoreHelper2.getOsTime();  
		} catch (Exception e) {
			res.sendRedirect(req.getContextPath() + "/InternalError.html");
		}
		Date trialIsOver = CoreHelper2.getTrialIsOver();  
		if (internetTime.compareTo(trialIsOver) > 0) {
			res.sendRedirect(req.getContextPath() + "/admin/Trail.html");
		}

		User user = (User) httpSession.getAttribute("user");
		if (user == null) {
			// res.sendRedirect(req.getContextPath());
			res.sendRedirect(req.getContextPath() + "/admin/login.xhtml");

		} else {
			if (!requestURI.startsWith(req.getContextPath()
					+ ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip
																// JSF
																// resources
																// (CSS/JS/Images/etc)
				res.setHeader("Cache-Control",
						"no-cache, no-store, must-revalidate"); // HTTP 1.1.
				res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
				res.setDateHeader("Expires", 0); // Proxies.
			}

			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
